#ifndef __MESSGAE_H__
#define __MESSAGE_H__

#pragma once
/**
 * 创建人：李江军
 * 时 间：2022-09-03
 * 说 明：消息基类、消息处理基类
 * 功 能：定义消息后调用基类后直接发送消息，接收消息的类基类消息处理基类后实现消息处理函数后即可
 *
 */

#include "macros.h"
#include "messageCenter.h"
#include <string>

template <typename M>
class BaseMessage;
template <typename M>
class BaseHandle;

class IHandle
{
public:
    virtual std::string getType() = 0;
};

class IMessage
{
public:
    virtual bool send(IHandle *bHandle) const = 0;
};

template <typename M>
class BaseMessage : public IMessage
{
public:
    BaseMessage() {}
    virtual ~BaseMessage() {}

    // 将消息类指针发送至消息中心
    virtual bool send() const;

    virtual void post(MessagePriority priority = MessagePriority::MP_COMMON) const;

private:
    virtual bool send(IHandle *pHandle) const;
};


template <typename M>
bool BaseMessage<M>::send() const
{
    return MessageCenter::getInstance()->sendMsg(this);
}

template <typename M>
void BaseMessage<M>::post(MessagePriority priority) const
{
    IMessage *m = (IMessage *)new M(*((M *)this));
    MessageCenter::getInstance()->pushMessgae(m, priority);
}

template <typename M>
bool BaseMessage<M>::send(IHandle *pHandle) const
{
    if (pHandle == nullptr)
    {
        perror("invalid handle");
        return false;
    }

    BaseHandle<M> *p = dynamic_cast<BaseHandle<M> *>(pHandle);
    if (p == nullptr)
    {
        perror("invalid BaseHandle");
        return false;
    }
    return p->handle((const M *)this);
}

template <typename M>
class BaseHandle : public IHandle
{
public:
    BaseHandle() { MessageCenter::getInstance()->attach(this); }
    virtual ~BaseHandle() { MessageCenter::getInstance()->detach(this); }

    virtual std::string getType() final;

    virtual bool handle(const M *pMsg) = 0;
};

template <typename M>
std::string BaseHandle<M>::getType()
{
    return typeid(M).name();
}

#endif // __MESSAGE_H__